﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;

using UncleBobWebService.Models;
using UncleBobWebService.ServiceRequester;


namespace UncleBobApplicantWebService.Controllers
{
    public class ApplicantJobListController : Controller
    {
        private UncleBobApplicantWebService.ApplicantWebService.WebServiceClient m_applicantClient = 
            new UncleBobApplicantWebService.ApplicantWebService.WebServiceClient();

        /*
         * ApplicantJobList : ActionResult
         * -------------------------------------------------------------------------------
         * Will redirect to the ApplicantJoblist View if the Job list can be be retrieved
         * from the database successfully. Otherwise, it will redirect to the Error page.
         */
        public ActionResult ApplicantJobList()
        {
            KioskUser user;

            if (!CreateListOfJobs())
            {
                TempData[SessionKeys.ERROR] = "Database Error: Could not retrieve Job List.";
                return RedirectToAction("Error", "Error");
            }

            // Get the list of jobs.
            List<JobModel> jobList = Session[SessionKeys.JOBSLIST] as List<JobModel>;

            // Get the list of applied jobs.
            RegisterModel regMod = Session[SessionKeys.USER] as RegisterModel;
            Message msg = new Message(MessageTypes.SERVICE_GET_USER_ALL_JOB_APPLICATIONS);
            msg.Data = regMod;
            msg = m_applicantClient.RequestService(msg);


            if (msg.Result)
            {
                user = msg.Data as KioskUser;
                user.Registration = regMod;
            }
            else
            {
                user = new KioskUser();
            }

            foreach (JobApplication jobApp in user.JobApplications.Values)
            {                
                JobModel removeJob = null;
                foreach (JobModel job in jobList)
                {
                    if (string.Compare(job.Title, jobApp.Job.Title) == 0)
                    {
                        removeJob = job;
                    }
                }
                if (removeJob != null)
                {
                    jobList.Remove(removeJob);
                }
            }

            return View(jobList);
        }

        /*
         * FormAction : ActionResult
         * --------------------------------------------------------------------------
         * Method will process the Applicant's job selection as selected in the view
         * and then will redirect to the ApplicantApplyController in order to begin
         * the application process.
         */
        [SessionExpiredFilter]
        public ActionResult FormAction(FormCollection collection)
        {
            // If the user hit the "Previous" button, go back to Applicant Main
            if (null != collection["previous"])
            {
                return RedirectToAction("MainMenu", "ApplicantMainMenu");
            }

            ApplicationQuestions questions = GetQuestionsByJobTitle(collection["answer"] as string);

            // If there questions are null, we have an error.
            if (null == questions || 0 == questions.TotalQuestions)
            {
                TempData[SessionKeys.ERROR] = "Database error: could not retrieve Application Questions.";
                return RedirectToAction("Error", "Error");
            }

            // save questions to the Session and start Application process
            Session[SessionKeys.QUESTIONS] = questions;

            return RedirectToAction("NextQuestion", "ApplicantApply");
        }

        /*
         * CreateListOfJobs : bool
         * -------------------------------------------------------------------------
         * If a List<JobModel> can be retrieved from the database, store the List in 
         * the Session and return "true". Otherwise, return "false".
         */
        private bool CreateListOfJobs()
        {
            // Create a new list of jobs and a corresponding message to query the DB
            Message msg = new Message(MessageTypes.SERVICE_GET_ALL_JOBS);    

            // Query the DB for the list of jobs and add it to the session.
            msg = m_applicantClient.RequestService(msg);

            // If we couldn't retrieve the JobList from the DB, we ran into an error
            if (null == (msg.Data as List<JobModel>))
            {
                return false;
            }
            else
            {
                Session.Add(SessionKeys.JOBSLIST, msg.Data as List<JobModel>);
                return true;
            }
        }

        /*
         * CreateQuestionsByJobTitle : ApplicationQuestions
         * --------------------------------------------------------------------------
         * If ApplicationQuestions can be retrieved from the DB, store them in the
         * Session and return "true". Otherwise, return "false".
         */
        private ApplicationQuestions GetQuestionsByJobTitle(string jobTitle)
        {
            // Request job questions from the database
            JobModel job = new JobModel();
            Message msg = new Message(MessageTypes.SERVICE_GET_JOB_BY_TITLE);

            // Look for the appropriate job the user selected 
            job.Title = jobTitle;
            msg.Data = job;
            msg = m_applicantClient.RequestService(msg);

            // Get questions associated with this job from the database and store in the session
            job = msg.Data as JobModel;
            Session[SessionKeys.JOB] = job;

            msg = new Message(MessageTypes.SERVICE_GET_JOB_QUESTIONS);
            msg.Data = job;
            msg = m_applicantClient.RequestService(msg);

            return msg.Data as ApplicationQuestions;
        }
    }
}
